package com.hanbang.mrcm_merchant.application;

import java.io.File;
import java.util.Timer;
import java.util.TimerTask;
import org.json.JSONException;
import org.json.JSONObject;
import com.hanbang.mrcm_merchant.R;
import com.hanbang.mrcm_merchant.announce.AnnounceActivity;
import com.hanbang.mrcm_merchant.base.BaseActivity;
import com.hanbang.mrcm_merchant.bean.UserInforData;
import com.hanbang.mrcm_merchant.utils.HttpInterfaces;
import com.hanbang.mrcm_merchant.utils.JsonHelper;
import com.hanbang.mrcm_merchant.utils.MyLog;
import com.hanbang.mrcm_merchant.utils.MyRequestCallBack;
import com.hanbang.mrcm_merchant.utils.MySharedPreferences;
import com.hanbang.mrcm_merchant.utils.MyToast;
import com.lidroid.xutils.exception.DbException;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.HttpHandler;
import com.lidroid.xutils.http.RequestParams;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.client.HttpRequest.HttpMethod;
import com.testin.agent.TestinAgent;
import com.testin.agent.TestinAgentConfig;
import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.widget.ImageView;
import android.widget.Toast;
import android.widget.ImageView.ScaleType;

public class WelcomeActivity extends BaseActivity {
	private int time = 3000;
	private Timer timer = new Timer();
	private boolean isToNext = false;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		ImageView imageView = new ImageView(this);
		imageView.setScaleType(ScaleType.CENTER_CROP);
		imageView.setImageResource(R.drawable.lead);
		setContentView(imageView);
		next();
		timer.schedule(new TimerTask() {

			@Override
			public void run() {
				while (isToNext) {
					myHandler.sendEmptyMessage(0x123);
					break;
				}

			}
		}, time);

	}

	@SuppressLint("HandlerLeak")
	Handler myHandler = new Handler() {
		public void handleMessage(android.os.Message msg) {
			super.handleMessage(msg);
			if (msg.what == 0x123) {
				timer.cancel();
				Intent intent = new Intent();
				intent.setClass(WelcomeActivity.this, AnnounceActivity.class);
				intent.addFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
				startActivity(intent);
				finish();
			}
		};
	};

	private void next() {
		if (isLogin(false)) {
			// 检查密码的正确性
			verifyLogin();
		} else {
			// 未登录
			isToNext = true;
		}

		String userInfo = userData == null ? "no_login" : userData.getMobile();
		// 云测
		TestinAgentConfig config = new TestinAgentConfig.Builder(this)
				.withAppKey("c920674") // Appkey of
										// your
										// appliation,
										// required
				.withAppChannel(null) // Channel of your application
				.withUserInfo(userInfo) // User infomation like login account of
										// user
				.withDebugModel(false) // Output the crash log in local if you
										// open debug mode
				.withErrorActivity(true) // Output the activity info in crash or
											// error log
				.withCollectNDKCrash(true) // Collect NDK crash or not if you
											// use our NDK
				.withOpenCrash(true) // Monitor crash if true
				.withReportOnlyWifi(false) // Report data only on wifi mode
				.withReportOnBack(true) // allow to report data when application
										// in background
				.build();
		TestinAgent.init(config);
	}

	HttpHandler<File> handler = null;

	// private void getServiceVersion() {
	// ((MyApplication) getApplication()).httpUtils.send(
	// HttpMethod.GET,
	// HttpInterfaces.updateApp + "&versioncode="
	// + SystemTools.getVersionCode(this),
	// new MyRequestCallBack<String>(this, null) {
	// @Override
	// public void onFailure(HttpException error, String msg) {
	// super.onFailure(error, msg);
	// next();
	// }
	//
	// @Override
	// public void onSuccess(ResponseInfo<String> responseInfo) {
	// super.onSuccess(responseInfo);
	// try {
	// JSONObject json = new JSONObject(
	// responseInfo.result.toString());
	// int status = json.getInt("status");
	// if (status == 1) {
	// String versionName = json
	// .getString("versionName");
	// final String path = json.getString("path");
	// MyDialog dialog = new MyDialog(
	// WelcomeActivity.this,
	// R.style.base_dialog, MODE.CONFIRM);
	// dialog.setTitle("版本更新");
	// dialog.setContent("检测到新版本，当前版本"
	// + SystemTools
	// .getVersionName(WelcomeActivity.this)
	// + ",最新版本" + versionName + ",是否下载更新？");
	// dialog.setOnClickCallback(new MyDialog.OnClickCallback() {
	//
	// @Override
	// public void onClick(MyDialog dialog,
	// Object number, Object content) {
	// if ((Integer) number == 0
	// || (Integer) number == 1) {
	// next();
	// } else if ((Integer) number == 2) {
	// // 确定 下载
	// final MyDialog dialog2 = new MyDialog(
	// WelcomeActivity.this,
	// R.style.base_dialog,
	// MODE.PROGRESS);
	// dialog2.setTitle("正在下载");
	// dialog2.setOnClickCallback(new MyDialog.OnClickCallback() {
	//
	// @Override
	// public void onClick(
	// MyDialog dialog,
	// Object number,
	// Object content) {
	// if (handler != null) {
	// handler.cancel();
	// MyToast.show(
	// WelcomeActivity.this,
	// "取消下载",
	// Toast.LENGTH_SHORT);
	// next();
	// }
	// }
	// });
	// dialog2.show();
	// MyRequestCallBack<File> callBack = new MyRequestCallBack<File>(
	// WelcomeActivity.this, null) {
	// public void onSuccess(
	// com.lidroid.xutils.http.ResponseInfo<File> responseInfo) {
	// super.onSuccess(responseInfo);
	// installApk(responseInfo.result);
	// dialog2.dismiss();
	// };
	//
	// public void onFailure(
	// HttpException error,
	// String msg) {
	// super.onFailure(error, msg);
	// dialog2.dismiss();
	// next();
	// };
	//
	// public void onLoading(
	// long total,
	// long current,
	// boolean isUploading) {
	// super.onLoading(total,
	// current,
	// isUploading);
	// Float countMb = ((int) ((total / 1024.0 / 1024.0) * 100)) / 100.0f;
	// Float currentMb = ((int) ((current / 1024.0 / 1024.0) * 100)) / 100.0f;
	// dialog2.setProgress((int) (current
	// / (total * 1.0) * 100));
	// dialog2.setMb(countMb,
	// currentMb);
	//
	// };
	// };
	// callBack.setRate(100);
	// handler = ((MyApplication) getApplication()).httpUtils.download(
	// SystemTools
	// .getHttpFileUrl(path),
	// MyApplication.otherPath
	// + File.separator
	// + "mrcm.apk",
	// callBack);
	// }
	// }
	// });
	//
	// dialog.show();
	//
	// } else {
	// next();
	// }
	// } catch (JSONException e) {
	// e.printStackTrace();
	// }
	//
	// }
	//
	// });
	// }

	// 安装apk
	// protected void installApk(File file) {
	// Intent intent = new Intent();
	// // 执行动作
	// intent.setAction(Intent.ACTION_VIEW);
	// // 执行的数据类型
	// intent.setDataAndType(Uri.fromFile(file),
	// "application/vnd.android.package-archive");
	// startActivityForResult(intent, 990);
	// }

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		// TODO Auto-generated method stub
		super.onActivityResult(requestCode, resultCode, data);
		Log.e("onActivityResult", requestCode + "  " + resultCode);
		if (requestCode == 990 && resultCode == 0) {
			// 取消安装了
			next();
		}
	}

	/*
	 * 如果已经保存密码 那么就检查此密码的正确性
	 */
	private void verifyLogin() {

		RequestParams params = new RequestParams();
		params.addBodyParameter("action", "seller_login");
		params.addBodyParameter("user_name", userData.getUser_name());
		params.addBodyParameter("password", userData.getPassword());
		httpUtils.send(HttpMethod.POST, HttpInterfaces.userLogin, params,
				new MyRequestCallBack<String>(this, null) {
					@Override
					public void onFailure(HttpException error, String msg) {
						super.onFailure(error, msg);
						isToNext = true;
					}

					@Override
					public void onSuccess(ResponseInfo<String> responseInfo) {
						super.onSuccess(responseInfo);
						try {
							JSONObject json = new JSONObject(
									responseInfo.result);
							int status = json.getInt("status");
							if (status == 1) {
								UserInforData userInforData = JsonHelper
										.parseObject(json, UserInforData.class);
								try {
									dbUtils.saveOrUpdate(userInforData);
									// 把id 保存在sp
									MySharedPreferences
											.setSharedPreferencesKeyAndValue(
													WelcomeActivity.this,
													MySharedPreferences.USER_DATA,
													"user_id",
													userInforData.getTrade_id());
									MyLog.e("login", "id保存成功");
									isToNext = true;
								} catch (DbException e) {
									e.printStackTrace();
									MyLog.e("login", "id保存失败");
									MyToast.show(WelcomeActivity.this, "登录失败",
											Toast.LENGTH_SHORT);
									MySharedPreferences
											.setSharedPreferencesKeyAndValue(
													WelcomeActivity.this,
													MySharedPreferences.USER_DATA,
													"user_id", -1);
									isToNext = true;
								}
							} else if (status == -100) {
								passwordIsError(true);
							}
						} catch (JSONException e) {
							e.printStackTrace();
							MyToast.show(WelcomeActivity.this, "登录失败",
									Toast.LENGTH_LONG);
						}
						isToNext = true;
					}
				});
	}

	@Override
	public void onBackPressed() {
	}

	@Override
	protected void onResume() {
		super.onResume();

	}

	@Override
	protected void onPause() {
		super.onPause();
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();

	}
}
